package	com.sdry.web.controller.plan;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.plan.DispatchBill;
import com.sdry.model.plan.DispatchBillDetail;
import com.sdry.model.plan.StorageArea;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.jyy.SimpleServise;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.lz.WarehouseService;
import com.sdry.service.plan.DispatchBillDetailService;
import com.sdry.service.plan.DispatchBillService;
import com.sdry.service.plan.StorageAreaService;
import com.sdry.utils.ResponseUtil;
/**
 *
 *@ClassName: DispatchBillController
 *@Description: 发货计划
 *@Author llm
 *@Date 2019-07-10 17:55:35
 *@version 1.0
*/
@Controller
@RequestMapping("/DispatchBill")
public class DispatchBillController{
	@Resource DispatchBillService DispatchBillService;
	@Resource SimpleServise simpleServise;
	@Resource StockOutOrderService stockOutService;
	@Resource DispatchBillDetailService dispatchBillDetailService;
	@Resource WarehouseService warehouseService;
	@Resource StorageAreaService storageAreaService;
	//声明一个Logger
	private final static Logger logger = LoggerFactory.getLogger(DispatchBillController.class);
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public String pageDispatchBill (Model model,HttpSession session,HttpServletResponse response) {
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		logger.info("session仓库id"+warehouse_id);
		List<Customer> customer_type0 = stockOutService.queryAllCustomerByType();
		model.addAttribute("customer_type0", customer_type0);
		logger.info("所有供应商"+JSONArray.fromObject(customer_type0));
		Long warehouseId = (Long)session.getAttribute("warehouse_id");
		List<Warehouse> allWarehouse = warehouseService.queryAllWarehouse(warehouseId);
		logger.info("仓库"+JSONArray.fromObject(allWarehouse));
		model.addAttribute("allWarehouse", allWarehouse);
		return "/plan/dispatchBill";
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public DispatchBill queryById(Long id) {
		DispatchBill param = DispatchBillService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<DispatchBill> queryAllByMution(DispatchBill param) {
		List<DispatchBill> list = DispatchBillService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(DispatchBill param,HttpServletResponse response){
		/*
		 * 条件分页查询内容
		 */
		List<DispatchBill> list = DispatchBillService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = DispatchBillService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(DispatchBill param, HttpServletResponse response){
		Long id = DispatchBillService.insert(param);
		try {
			response.getWriter().print(id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pLinsert")
	public void pLinsert(DispatchBill param,Long[] materiel_ids,int[] shipments_quantitys,HttpSession session, HttpServletResponse response){
		logger.info("详情批量添加插入返回id"+JSONArray.fromObject(param)+materiel_ids+shipments_quantitys);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcSysUserEntity user = (ZcSysUserEntity)session.getAttribute("user");
		param.setUser_id(user.getId());
		param.setCreate_date(sdf.format(new Date()));
		param.setStatus(0+"");
		logger.info("主表添加内容"+JSONArray.fromObject(param));
    	Long id = DispatchBillService.insert(param);
    	logger.info("主表添加返回id"+id);
		if(null != id && id > 0){
			DispatchBillDetail detail = new DispatchBillDetail();
			detail.setDispatchId(id);
			for (int i = 0; i < materiel_ids.length; i++) {
				//根据物料获取线边库库存和安全库存
				StorageArea storageArea = new StorageArea();
				storageArea.setMaterielId(materiel_ids[i]);
	        	List<StorageArea> li = storageAreaService.queryAllByMution(storageArea);
	        	if(li.size() > 0){
	        		//线边库存
	        		detail.setStorageQuantity(li.get(0).getMaterielQuantity());
	        		if(null != li.get(0).getLowers()) {
	        			//线边安全库存
	        			detail.setAstock(li.get(0).getLowers());
	        		}else {
	        			//线边安全库存
	        			detail.setAstock(0);
	        		}
	        	}else{
	        		//线边库存
	        		detail.setStorageQuantity(0);
	        		//线边安全库存
	        		detail.setAstock(0);
	        	}
				detail.setMaterielId(materiel_ids[i]);
				detail.setShipmentsQuantity(shipments_quantitys[i]);
				logger.info("详情表添加内容"+JSONArray.fromObject(detail));
				dispatchBillDetailService.insert(detail);
			}
		}
		try {
			response.getWriter().print(id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(DispatchBill param,HttpServletResponse response){
		Integer count = DispatchBillService.update(param);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pLupdate")
	public void pLupdate(DispatchBill param,Long[] materiel_ids,int[] shipments_quantitys,HttpServletResponse response){
		Integer count = DispatchBillService.update(param);
		if(null != count && count > 0){
			dispatchBillDetailService.deleteByDispatchIds(param.getId()+"");
			DispatchBillDetail detail = new DispatchBillDetail();
			detail.setDispatchId(param.getId());
			for (int i = 0; i < materiel_ids.length; i++) {
				//根据物料获取线边库库存和安全库存
				StorageArea storageArea = new StorageArea();
				storageArea.setMaterielId(materiel_ids[i]);
	        	List<StorageArea> li = storageAreaService.queryAllByMution(storageArea);
	        	if(li.size() > 0){
	        		//线边库存
	        		detail.setStorageQuantity(li.get(0).getMaterielQuantity());
	        		if(null != li.get(0).getLowers()) {
	        			//线边安全库存
	        			detail.setAstock(li.get(0).getLowers());
	        		}else {
	        			//线边安全库存
	        			detail.setAstock(0);
	        		}
	        	}else{
	        		//线边库存
	        		detail.setStorageQuantity(0);
	        		//线边安全库存
	        		detail.setAstock(0);
	        	}
				detail.setMaterielId(materiel_ids[i]);
				detail.setShipmentsQuantity(shipments_quantitys[i]);
				logger.info("详情表添加内容"+JSONArray.fromObject(detail));
				dispatchBillDetailService.insert(detail);
			}
		}
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		logger.info("根据主键拼接的字符串删除返回影响行数"+ids);
		ids=ids.replace("'",""); 
		Integer count = DispatchBillService.delete(ids);
		logger.info("根据主键拼接的字符串删除返回影响行数"+count);
		if(null != count && count > 0){
			dispatchBillDetailService.deleteByDispatchIds(ids);
		}
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
